package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"map-master/cache"
	"map-master/moderl"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	content := c.PostForm("content")
	types := c.PostForm("types")

	if title == "" || author == "" || content == "" || types == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不能为空",
		})
		return
	}
	data := moderl.Detail{
		Title:   title,
		Author:  author,
		Types:   types,
		Content: content,
	}
	err := moderl.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	offset := (page - 1) * size
	var fy []moderl.Detail
	redis_key := "list_id" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderl.DB.Offset(offset).Limit(size).Find(&fy)
		jsonData, _ := json.Marshal(&fy)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &fy)
	}

	var count int64
	moderl.DB.Model(&moderl.Detail{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"count": count,
		"msg":   fy,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var de moderl.Detail
	redis_key := "de_id" + id
	moderl.DB.Where("id = ?", id).Find(&de)
	jsonData, _ := json.Marshal(de)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  de,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")

	redis_key := "del_id" + id
	moderl.DB.Where("id = ?", id).Delete(&moderl.Detail{})
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "删除成功",
	})
	return
}
